/**
 * 
 */
package com.swg.cocobox.message.example;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import com.swg.cocobox.message.ClientInfo;
import com.swg.cocobox.message.ClientInfoParser;
import com.swg.cocobox.message.Message;
import com.swg.cocobox.message.MessageContext;
import com.swg.cocobox.message.MessageContext.MessageEncoding;
import com.swg.cocobox.message.MessageFactory;
import com.swg.cocobox.message.MessagePackage;
import com.swg.cocobox.message.MessageServer;
import com.swg.cocobox.message.event.MessageEvent;
import com.swg.cocobox.message.event.MessageEventProcessor;
import com.swg.cocobox.message.event.MessageEventSupport;

/**
 * @author satriaprayoga
 *
 */
public class SimpleMessageServer extends MessageServer{
	
	private final Logger logger=Logger.getLogger(getClass());

	public SimpleMessageServer(InetAddress address, int port)throws IOException {
		super(address, port);
		setEventProcessor(new MessageEventProcessor());
		setEventSupport(new MessageEventSupport(this));
		addListener(new SimpleMessageEventListener());
	}

	@Override
	protected void handlePackage(SocketChannel channel,MessagePackage messagePackage) {
		int type=messagePackage.getType();
		logger.debug("message package type: "+type);
		messagePackage.removeType();
		if(type==MessageContext.LOGIN){
			handleLogin(channel, messagePackage.getMessageData());
		}else if(type==MessageContext.LOGOUT){
			handleLogout(channel, messagePackage.getMessageData());
		}else if(type==MessageContext.MESSAGE){
			handleMessage(channel, messagePackage.getMessageData());
		}
	}
	
	private void handleLogin(SocketChannel channel,byte[] data){
		ClientInfoParser parser=MessageContext.getClientInfoParser(MessageEncoding.ASCII);
		ClientInfo info=parser.parseClientInfo(data);
		
		MessageEvent event=getEventSupport().fireEvent(channel, MessageContext.RECEIVE_EVENT, info);
		getEventProcessor().queueEvent(event);
	}
	
	private void handleLogout(SocketChannel channel,byte[] data){
		ClientInfoParser parser=MessageContext.getClientInfoParser(MessageEncoding.ASCII);
		ClientInfo info=parser.parseClientInfo(data);
		MessageEvent event=getEventSupport().fireEvent(channel, MessageContext.RECEIVE_EVENT, info);
		getEventProcessor().queueEvent(event);
	}

	private void handleMessage(SocketChannel channel,byte[] data){
		MessageFactory messageFactory=MessageContext.getMessageFactory(MessageEncoding.ASCII);
		Message message=messageFactory.parseMessage(data);
		MessageEvent event=getEventSupport().fireEvent(channel, MessageContext.RECEIVE_EVENT, message);
		getEventProcessor().queueEvent(event);
	}
	
	public static void main(String[] args) throws IOException{
		MessageServer server=new SimpleMessageServer(InetAddress.getByName("localhost"),1234);
		server.startServer();
	}

}
